package com.kaifamiao.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class WriteChannelTest {

    public static void main(String[] args) throws IOException {

        final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

        Path path = Path.of("channel.txt");
        ByteChannel channel = Files.newByteChannel(path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        buffer.put( "小芳:".getBytes(StandardCharsets.UTF_8) );
        buffer.put( "最近上课睡觉可好?".getBytes(StandardCharsets.UTF_8) );
        System.out.println( buffer );

        buffer.flip(); // "反转缓冲区"
        // 通过通道将缓冲区中[0, limit)之间的的内容输出
        channel.write( buffer );
        buffer.clear();

        buffer.put( "最近天气冷，上课睡觉别感冒。".getBytes(StandardCharsets.UTF_8) );

        buffer.flip();
        channel.write( buffer );
        buffer.clear();

        channel.close();
    }

}
